package custom.base.ui.activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;


import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import com.jaeger.library.StatusBarUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;
import custom.base.R;
import custom.base.http.AppApi;
import custom.base.http.listener.AliveCallback;
import custom.base.http.retrofit.IRequest;
import custom.base.log.MLog;
import custom.base.utils.AppUtils;
import custom.base.utils.BroadcastUtil;
import custom.base.utils.KeyBoardUtils;
import custom.base.utils.TxtUtil;
import retrofit2.Call;
import retrofit2.Callback;

public abstract class BaseActivity extends AppCompatActivity implements ActivityInterface,
        View.OnClickListener, AliveCallback {
    /**
     * 任务队列列表
     */
    List<Call> requestList;
    /**
     * 网络请求服务
     */
    public AppApi appApi;

    /**
     * 返回按钮对象
     */
    private View backBtn;
    /**
     * 标题栏文本控件
     */
    private TextView tvTitle;
    /**
     * 标题名称
     */
    @NonNull
    private String titleName = "";


    @Override
    protected final void onCreate(Bundle savedInstanceState) {
        befordCreateView(savedInstanceState);
        super.onCreate(savedInstanceState);
        if (initStatusBar()) {
            StatusBarUtil.setColor(getActivity(), Color.WHITE, 0);
            StatusBarUtil.setLightMode(getActivity());
        }
        AppManager.getInstance().addActivity(this);

        int layoutID = getLayoutID();
        if (layoutID != 0) {
            setContentView(layoutID);
        } else {
            setContentView(getLayoutView());
        }
        //需要加入
        ButterKnife.bind(this);

        initNetWork();
        init(savedInstanceState);
    }


    /**
     * 基础初始化
     */
    private void initNetWork() {
        requestList = new ArrayList<>();
        appApi = IRequest.getInstance(this).getAppApi();
    }

    /**
     * 添加请求访问，调用此方法添加的话，会在activity结束的时候取消接口的请求，如果已经请求成功的话则忽略
     */
    protected Call addRequestCall(Call call, Callback callback) {
        if (call != null && requestList != null)
            requestList.add(call);
        if (call != null)
            call.enqueue(callback);
        return call;
    }

    /**
     * 取消所有任务
     */
    protected void cancelAllRequestCall() {
        if (requestList == null)
            return;
        //循环取消未完成的任务
        if (requestList != null) {
            for (int i = 0; i < requestList.size(); i++) {
                Call call = requestList.get(i);
                MLog.d(getMTag(), "移除请求任务: " + call);
                call.cancel();
            }
            //清除所有缓存列表
            requestList.clear();
        }
    }

    /**
     * 方法回调顺序
     * 1.initView
     * 2.initClss
     * 3.initData
     * 4.initListener
     *
     * @param savedInstanceState
     */
    private void init(@NonNull Bundle savedInstanceState) {
        titleName = isInitBackBtn();
        initBackViews();
//        if (isInitBackBtn() != null)
        initBackBtn();

        initView(savedInstanceState);
        initObject(savedInstanceState);
        initData(savedInstanceState);
        initListener();
    }

    private void initBackViews() {
//        try {
//            backBtn = ButterKnife.findById(this, R.id.top_bar_back);
//            tvTitle = ButterKnife.findById(this, R.id.top_bar_title_name);
//        } catch (Exception e) {
//            MLog.e(getMTag(), e.getMessage());
//        }
    }

    /**
     * 初始化back按钮事件，及title名称赋值
     */
    private void initBackBtn() {
        try {
            backBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    onBackIconClick();
                }
            });
            if (titleName != null && !"".equals(titleName))
                tvTitle.setText(titleName);
        } catch (Exception e) {
            MLog.e(getMTag(), e.getMessage());
        }
    }

    /**
     * 返回图标按钮的点击
     */
    protected void onBackIconClick() {
        finish();
    }

    /**
     * 是否初始化返回按钮
     *
     * @return 如果不想baseactivity自动设置监听返回按钮的话就传回null，
     * 系统则不会自动设置监听,但是会初始化控件
     */
    protected String isInitBackBtn() {
        return null;
    }

    /**
     * 得到返回按钮控件
     */
    public View getBackBtnView() {
        return backBtn;
    }

    /**
     * 得到标题文本控件
     */
    public TextView getTitleView() {
        return tvTitle;
    }

    /**
     * 设置标题文本
     */
    public void setTitleText(String str) {
        if (tvTitle != null && !TxtUtil.isEmpty(str))
            tvTitle.setText(str);
    }

    @Override
    protected void onResume() {
        super.onResume();
//        MobclickAgent.onResume(this);
        //为了不影响效率这个版本不开放震动打开调试模式的功能
//        ShakeManager.getInstance(getApplicationContext()).start();
    }

    @Override
    protected void onPause() {
        KeyBoardUtils.hideKeyboard(this);
        super.onPause();
//        MobclickAgent.onPause(this);
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (!AppUtils.isAppOnForeground(this)) {//如果app切换到后台发送后台处理广播
            BroadcastUtil.getInstance().sendEmptyBoradcast(this, BroadcastUtil.APP_ON_BACKGROUND);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
//        unbinder.unbind();
        AppManager.getInstance().removeActivity(this);

        //循环取消未完成的任务
        if (requestList != null) {
            for (int i = 0; i < requestList.size(); i++) {
                Call call = requestList.get(i);
                MLog.d(getMTag(), "移除请求任务: " + call);
                call.cancel();
            }
            //清除所有缓存列表
            requestList.clear();
            requestList = null;
        }

    }

    @Override
    public final void onClick(View v) {
        onClick(v, v.getId());
    }

    /**
     * 单击回调
     *
     * @param v       点击的view
     * @param clickID 点击的控件id
     */
    public void onClick(View v, int clickID) {

    }


    /**
     * 默认不适用此方法，在子类里可以重构他
     */
    @Override
    public View getLayoutView() {
        return null;
    }

    /**
     * 是否设置statusBar的 状态透明值等，子类复写可以取消父类的方法
     */
    public boolean initStatusBar() {
        return true;
    }

    //=====================setContentView 前回调

    @Override
    public void befordCreateView(@NonNull Bundle savedInstanceState) {
        //删除保存的Fragment，也可以重写onSaveInstanceState方法不让其保存，为了保证在fragment被回收后不会导致异常崩溃
        if (savedInstanceState != null) {
            savedInstanceState.putParcelable("android:support:fragments", null);
        }
    }

    //=================创建后回调
    @Override
    public void initView(@NonNull Bundle savedInstanceState) {

    }

    @Override
    public void initObject(@NonNull Bundle savedInstanceState) {

    }

    @Override
    public void initData(@NonNull Bundle savedInstanceState) {

    }

    @Override
    public void initListener() {

    }

    /**
     * 得到本类名
     */
    protected String getMTag() {
        return getResources().getString(R.string.app_name) + "#" + getClass().getSimpleName();
    }


    //============================================网络回调

    //=============================================字体设置回调
//    @Override
//    protected void attachBaseContext(Context newBase) {
//        super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase));
//    }

    /**
     * 在activity销毁时是否自动保存fragment的状态，本方法为避免异常默认是false
     */
    protected boolean isCacheFragmentOnDestory() {
        return false;
    }

    @Override
    public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
        if (isCacheFragmentOnDestory()) {
            super.onSaveInstanceState(outState, outPersistentState);//为了避免移除在懈怠了fragment的activity中都注释掉了保存状态
        }
    }

    /**
     * 快捷开启activity
     */
    public void startActivity(Class<?> cls) {
        startActivity(new Intent(this, cls));
    }

    protected Activity getContext() {
        return this;
    }

    protected Activity getActivity() {
        return this;
    }

    protected AliveCallback getALiveNetCallback() {
        return this;
    }

    /**
     * 界面是否存活
     */
    public boolean activityIsAlive() {
        if (getActivity() == null) return false;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            return !(getActivity().isDestroyed() || getActivity().isFinishing());
        } else {
            return !getActivity().isFinishing();
        }
    }

    @Override
    public boolean isAlive() {
        return activityIsAlive();
    }

    @Override
    public Activity currentContext() {
        return getActivity();
    }

    /**
     * 设置是否全屏
     */
    public void setFullScreen(boolean fullScreen) {
        if (fullScreen) {
            //全屏
            getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                    WindowManager.LayoutParams.FLAG_FULLSCREEN);
        } else {
            //全屏
            getWindow().clearFlags(
                    WindowManager.LayoutParams.FLAG_FULLSCREEN);
        }
    }
}
